﻿@page "/stockin"
@page "/stockin/{Id:int?}"
@using Microsoft.EntityFrameworkCore
@using Wms.Core.Entities
@inject Wms.Data.WarehouseDbContext Db
@inject NavigationManager Navigation

<h3>新增入库单</h3>

<div class="mb-3">
    <label>单号:</label>
    <input class="form-control" @bind="order.OrderNo" />
</div>
<div class="mb-3">
    <label>入库类型:</label>
    <InputSelect @bind-Value="order.Type" class="form-control">
        <option value="">请选择类型</option>
        <option value="@StockInType.Purchase">采购入库</option>
        <option value="@StockInType.Production">生产入库</option>
        <option value="@StockInType.Return">退货入库</option>
    </InputSelect>
</div>
<div class="mb-3">
    <label>日期:</label>
    <input type="date" class="form-control" @bind="order.Date" />
</div>

<hr />

<h5>入库明细</h5>
<table class="table">
    <thead>
        <tr><th>物料</th><th>库位</th><th>数量</th></tr>
    </thead>
    <tbody>
        @foreach (var d in details)
        {
            <tr>
                <td>
                    <InputSelect @bind-Value="d.ItemId" class="form-control">
                        <option value="">请选择物料</option>
                        @foreach (var item in allItems)
                        {
                            <option value="@item.Id">@item.Name</option>
                        }
                    </InputSelect>
                </td>
                <td>
                    <InputSelect @bind-Value="d.LocationId" class="form-control">
                        <option value="">请选择库位</option>
                        @foreach (var loc in allLocations)
                        {
                            <option value="@loc.Id">@loc.Name</option>
                        }
                    </InputSelect>
                </td>
                <td>
                    <input type="number" class="form-control" @bind="d.Quantity" />
                </td>
            </tr>
        }
    </tbody>
</table>
<button class="btn btn-secondary" @onclick="AddRow">+ 新增行</button>

<hr />
<button class="btn btn-primary" @onclick="SaveOrder">保存</button>
<button class="btn btn-outline-secondary" @onclick="Back">返回</button>

@code {
    [Parameter] public int? Id { get; set; }   // 可选参数
    private StockInOrder order = new StockInOrder
        {
            OrderNo = $"IN-{DateTime.Now:yyyyMMddHHmmss}",
            Date = DateTime.Now
        };

    private List<StockInDetailDto> details = new();
    private List<Item> allItems = new();
    private List<Location> allLocations = new();

    protected override async Task OnInitializedAsync()
    {
        allItems = await Db.Items.ToListAsync();
        allLocations = await Db.Locations.ToListAsync();  // 加载库位

        if (Id.HasValue) // 编辑模式
        {
            order = await Db.StockInOrders
                .Include(o => o.Details)
                .FirstOrDefaultAsync(o => o.Id == Id.Value);

            if (order != null)
            {
                // 把数据库里的明细转成 DTO
                details = order.Details.Select(d => new StockInDetailDto
                    {
                        ItemId = d.ItemId,
                        LocationId = d.LocationId,
                        Quantity = d.Quantity
                    }).ToList();
            }
        }
        else // 新增模式
        {
            order = new StockInOrder
                {
                    OrderNo = $"IN-{DateTime.Now:yyyyMMddHHmmss}",
                    Date = DateTime.Now
                };
            AddRow();
        }
    }

    private void AddRow()
    {
        details.Add(new StockInDetailDto());
    }

    private async Task SaveOrder()
    {
        using var tx = await Db.Database.BeginTransactionAsync();

        if (Id.HasValue) // 编辑模式
        {
            var existingOrder = await Db.StockInOrders
                .Include(o => o.Details)
                .FirstOrDefaultAsync(o => o.Id == Id.Value);

            if (existingOrder != null)
            {
                existingOrder.OrderNo = order.OrderNo;
                existingOrder.Date = order.Date;

                Db.StockInDetails.RemoveRange(existingOrder.Details);

                existingOrder.Details = details
                    .Where(d => d.ItemId > 0 && d.LocationId > 0 && d.Quantity > 0)
                    .Select(d => new Wms.Core.Entities.StockInDetail
                        {
                            ItemId = d.ItemId,
                            LocationId = d.LocationId,
                            Quantity = d.Quantity
                        }).ToList();
            }
        }
        else // 新增模式
        {
            order.Details = details
                .Where(d => d.ItemId > 0 && d.LocationId > 0 && d.Quantity > 0)
                .Select(d => new Wms.Core.Entities.StockInDetail
                    {
                        ItemId = d.ItemId,
                        LocationId = d.LocationId,
                        Quantity = d.Quantity
                    }).ToList();

            Db.StockInOrders.Add(order);
        }

        await Db.SaveChangesAsync();

        // 更新库存
        foreach (var d in order.Details)
        {
            var inventory = await Db.Inventories
                .FirstOrDefaultAsync(i => i.ItemId == d.ItemId && i.LocationId == d.LocationId);

            if (inventory != null)
                inventory.Quantity += d.Quantity;
            else
                Db.Inventories.Add(new Wms.Core.Entities.Inventory
                    {
                        ItemId = d.ItemId,
                        LocationId = d.LocationId,
                        Quantity = d.Quantity,
                        BatchNo = $"B{DateTime.Now:yyyyMMdd}"
                    });
        }

        await Db.SaveChangesAsync();
        await tx.CommitAsync();

        Navigation.NavigateTo("/stockin-list");
    }

    private void Back()
    {
        Navigation.NavigateTo("/stockin-list");
    }

    public class StockInDetailDto
    {
        public int ItemId { get; set; }
        public int LocationId { get; set; }
        public int Quantity { get; set; }
    }
}
